<?php

namespace App\Exceptions;

use App\Lib\Util\ErrorMessage;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Throwable  $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Throwable $exception)
    {
        //某些类型的exception，可以推到报警等
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $exception)
    {
        Log::error(
            '[' . $exception->getCode() . '] ' . $exception->getMessage(),
            [
                'url' => $request->fullUrl(),
                'request' => $request,
                'exception' => $exception,
            ]
        );

        $message = ($exception->getMessage() != '') ?
            $exception->getMessage() :
            ErrorMessage::getMessage($exception->getCode());

        return response()->json([
            'code' => $exception->getCode(),
            'message' => $message
        ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);

    }
}
